﻿<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>销售退货管理系统</title>
    <style>
        body {
            margin: 0;
            padding: 0;
            font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", Arial, sans-serif;
            background-color: #f5f7fa;
        }

        #tableBlock {
            margin: 20px auto;
            width: 100%;
            max-width: max-content;
            padding-bottom: 20px;
            box-shadow: 0 0 10px 4px rgba(0, 0, 0, 0.1);
            background-color: #fff;
            border-radius: 6px;
        }

        .search-area {
            padding: 20px;
            border-bottom: 0px solid #ebeef5;
        }

        .formTableInput, .formTableSelect {
            display: inline-block;
            width: 180px;
        }

        .buttonBlock {
            height: 40px;
            width: 100%;
            padding: 20px;
            gap: 10px;
            margin-bottom: 15px;
            flex-wrap: wrap;
        }

        .pagination-container {
            margin-top: 20px;
            display: flex;
            justify-content: flex-end;
            padding: 0 20px;
        }

        .audit-textarea {
            margin-top: 15px;
            width: 100%;
        }

        /* 操作列按钮间距 */
        .operate-btn {
            margin-right: 8px;
        }

        .btnAndTable {
            margin: 0 auto;
            padding: 0 20px;
        }

        .search-row {
            display: flex;
            flex-wrap: wrap;
            gap: 20px;
            margin-bottom: 15px;
        }

        .search-item {
            display: flex;
            align-items: center;
        }

            .search-item label {
                min-width: 80px;
                text-align: right;
                margin-right: 10px;
            }

        .status-tag {
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: bold;
        }

        .status-draft {
            background-color: #f0f0f0;
            color: #666;
        }

        .status-pending {
            background-color: #e6f7ff;
            color: #1890ff;
        }

        .status-rejected {
            background-color: #fff2f0;
            color: #ff4d4f;
        }

        .status-approved {
            background-color: #f6ffed;
            color: #52c41a;
        }

        .status-closed {
            background-color: #f5f5f5;
            color: #8c8c8c;
        }
    </style>
</head>
<body>
    <div id="app" class="common-layout" style="max-width: max-content;">
        <div id="tableBlock">
            <!-- 查询区域 -->
            <div class="search-area">
                <div class="search-row">
                    <div class="search-item">
                        <label>退货单号：</label>
                        <el-input type="text" v-model="searchForm.returnOrderNo" class="formTableInput" placeholder="请输入退货单号"></el-input>
                    </div>
                    <div class="search-item">
                        <label>客户：</label>
                        <el-select v-model="searchForm.customerId" class="formTableSelect" placeholder="请选择客户">
                            <el-option label="全部" value=""></el-option>
                            <el-option v-for="customer in customerOptions" :key="customer.id" :label="customer.name" :value="customer.id"></el-option>
                        </el-select>
                    </div>
                    <div class="search-item">
                        <label>销售人员：</label>
                        <el-input type="text" v-model="searchForm.sellerBy" class="formTableInput" placeholder="请输入销售人员"></el-input>
                    </div>
                    <div class="search-item">
                        <label>订单状态：</label>
                        <el-select v-model="searchForm.orderStatus" class="formTableSelect" placeholder="请选择订单状态">
                            <el-option label="全部" value=""></el-option>
                            <el-option label="草稿" value="0"></el-option>
                            <el-option label="待审核" value="1"></el-option>
                            <el-option label="已驳回" value="2"></el-option>
                            <el-option label="已审核" value="3"></el-option>
                            <el-option label="已关闭" value="4"></el-option>
                        </el-select>
                    </div>
                    <el-button type="default" v-on:click="resetForm">重置</el-button>
                    <el-button type="primary" v-on:click="searchTable">查询</el-button>
                    <el-button type="default">高级搜索</el-button>
                </div>
                <!-- 操作按钮区域 -->
                <div class="buttonBlock">
                    <el-button type="primary" v-on:click="addSalesReturn">新增</el-button>
                    <el-button type="default" v-on:click="editSalesReturn">编辑</el-button>
                    <el-button type="default" v-on:click="deleteSalesReturn">删除</el-button>
                    <el-button type="default" v-on:click="copySalesReturn">复制</el-button>
                    <el-button type="default" v-on:click="exportTable">导出</el-button>
                    <el-button type="default" v-on:click="importSalesReturn">导入</el-button>
                    <el-button type="success" v-on:click="refreshTable">刷新</el-button>
                </div>
            </div>

            <!-- 表格区域 -->
            <div class="btnAndTable">
                <el-table :data="paginatedData"
                          style="width: 100%; margin-top: 10px"
                          v-on:selection-change="handleSelectionChange"
                          ref="multipleTable"
                          stripe
                          border>
                    <el-table-column fixed type="selection" width="50"></el-table-column>
                    <el-table-column fixed label="退货单号" width="150">
                        <template #default="scope">
                            <span style="color: #10b981; cursor: pointer;" v-on:click="jumpToDetail(scope.row)">
                                {{ scope.row.returnOrderNo }}
                            </span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="customerName" label="客户名称" width="150"></el-table-column>
                    <el-table-column prop="sellerBy" label="销售人员" width="120"></el-table-column>
                    <el-table-column prop="returnDate" label="退货日期" width="120">
                        <template #default="scope">
                            {{ formatDate(scope.row.returnDate) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="returnReason" label="退货原因" width="150"></el-table-column>
                    <el-table-column prop="orderStatus" label="订单状态" width="100">
                        <template #default="scope">
                            <span :class="['status-tag', getStatusClass(scope.row.orderStatus)]">
                                {{ getStatusText(scope.row.orderStatus) }}
                            </span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="auditorBy" label="审核人" width="120"></el-table-column>
                    <el-table-column prop="auditorTime" label="审核时间" width="160">
                        <template #default="scope">
                            {{ formatDateTime(scope.row.auditorTime) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="auditorComment" label="审核意见" width="180"></el-table-column>
                    <el-table-column prop="createBy" label="创建人" width="100"></el-table-column>
                    <el-table-column prop="createTime" label="创建时间" width="160">
                        <template #default="scope">
                            {{ formatDateTime(scope.row.createTime) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="remarks" label="备注" width="200"></el-table-column>

                    <!-- 操作列：按状态动态显示按钮 -->
                    <el-table-column fixed="right" label="操作" min-width="130">
                        <template #default="scope">
                            <!-- 1. 草稿(0)/待审核(1)状态：显示【编辑】【删除】 -->
                            <el-button v-if="scope.row.orderStatus === '0' || scope.row.orderStatus === '1'"
                                       class="operate-btn"
                                       link type="primary" size="default"
                                       v-on:click="handleEdit(scope.row)">
                                编辑
                            </el-button>
                            <el-button v-if="scope.row.orderStatus === '0' || scope.row.orderStatus === '1'"
                                       class="operate-btn"
                                       link type="danger" size="default"
                                       v-on:click="deleteSingleSalesReturn(scope.row)">
                                删除
                            </el-button>

                            <!-- 2. 已驳回(2)状态：显示【编辑】【撤销】 -->
                            <el-button v-if="scope.row.orderStatus === '2'"
                                       class="operate-btn"
                                       link type="primary" size="default"
                                       v-on:click="handleEdit(scope.row)">
                                编辑
                            </el-button>
                            <el-button v-if="scope.row.orderStatus === '2'"
                                       class="operate-btn"
                                       link type="warning" size="default"
                                       v-on:click="handleRejectCancel(scope.row)">
                                撤销
                            </el-button>

                            <!-- 3. 已审核(3)状态：显示【关闭】 -->
                            <el-button v-if="scope.row.orderStatus === '3'"
                                       class="operate-btn"
                                       link type="warning" size="default"
                                       v-on:click="closeSalesReturn(scope.row)">
                                关闭
                            </el-button>

                            <!-- 4. 已关闭(4)状态：显示【启用】 -->
                            <el-button v-if="scope.row.orderStatus === '4'"
                                       class="operate-btn"
                                       link type="success" size="default"
                                       v-on:click="enableSalesReturn(scope.row)">
                                启用
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>

            <!-- 分页区域 -->
            <div class="pagination-container">
                <el-pagination v-model:current-page="currentPage"
                               v-model:page-size="pageSize"
                               :page-sizes="[10, 20, 50, 100]"
                               :total="total"
                               layout="total, sizes, prev, pager, next, jumper"
                               v-on:size-change="handleSizeChange"
                               v-on:current-change="handleCurrentChange">
                </el-pagination>
            </div>
        </div>
    </div>

    <script>
        const { createApp, ref, onMounted, computed } = Vue;
        const { ElMessageBox, ElMessage, ElNotification } = ElementPlus;

        // 状态映射配置：字符串值 -> 文字说明 -> 样式类
        const STATUS_CONFIG = {
            '0': { text: '草稿', class: 'status-draft' },
            '1': { text: '待审核', class: 'status-pending' },
            '2': { text: '已驳回', class: 'status-rejected' },
            '3': { text: '已审核', class: 'status-approved' },
            '4': { text: '已关闭', class: 'status-closed' }
        };

        const app = createApp({
            setup() {
                // -------------------------- 1. 基础数据初始化 --------------------------
                // 初始化加载数据
                const refreshData = async () => {
                    try {
                        const response = await axios.post('/OmSalesReturn/GetAll');

                        if (response.data.code === 200) {
                            tableData.value = response.data.data;
                            ElMessage.success('销售退货数据加载成功');
                        }
                    } catch (error) {
                        console.error('加载出错:', error);
                        ElMessage.error('数据加载失败，请重试');
                    }
                };

                // 加载客户选项
                const loadCustomerOptions = async () => {
                    try {
                        const response = await axios.post('/OmSalesReturn/CustomerAll');
                        if (response.data.code === 200) {
                            customerOptions.value = response.data.data;
                        }
                    } catch (error) {
                        console.error('加载客户选项出错:', error);
                    }
                };

                // 搜索表单
                const searchForm = ref({
                    returnOrderNo: '',
                    customerId: '',
                    sellerBy: '',
                    orderStatus: ''
                });

                // 客户选项
                const customerOptions = ref([]);

                // 表格数据
                const tableData = ref([]);

                // 选中行数据
                const selectedRows = ref([]);
                // 表格实例
                const multipleTable = ref(null);

                // -------------------------- 2. 分页逻辑 --------------------------
                const currentPage = ref(1);
                const pageSize = ref(10);
                const total = computed(() => tableData.value.length);
                const paginatedData = computed(() => {
                    const start = (currentPage.value - 1) * pageSize.value;
                    const end = start + pageSize.value;
                    return tableData.value.slice(start, end);
                });

                const handleSizeChange = (val) => {
                    pageSize.value = val;
                    currentPage.value = 1;
                };

                const handleCurrentChange = (val) => {
                    currentPage.value = val;
                    if (multipleTable.value) {
                        multipleTable.value.clearSelection();
                        selectedRows.value = [];
                    }
                };

                // -------------------------- 3. 状态转换辅助方法 --------------------------
                // 根据状态值获取显示文字
                const getStatusText = (status) => {
                    return STATUS_CONFIG[status]?.text || '未知状态';
                };

                // 根据状态值获取样式类
                const getStatusClass = (status) => {
                    return STATUS_CONFIG[status]?.class || '';
                };

                // -------------------------- 5. 核心操作方法 --------------------------
                // 5.1 选中行变化
                const handleSelectionChange = (val) => {
                    selectedRows.value = val;
                };

                // 5.2 编辑（仅草稿0/待审核1/已驳回2可执行）
                const handleEdit = (row) => {
                    // 二次校验状态
                    const allowEditStatus = ['0', '1', '2'];
                    if (!allowEditStatus.includes(row.orderStatus)) {
                        ElMessage({
                            type: 'error',
                            message: `当前「${getStatusText(row.orderStatus)}」状态不允许编辑！`
                        });
                        return;
                    } else {
                        ElNotification({
                            title: '编辑销售退货单',
                            message: `编辑销售退货单：${row.returnOrderNo}`,
                            type: 'info'
                        });
                        window.location.href = `/OmSalesReturn/Edit?id=${row.salesReturnId}`;
                    }
                };

                // 5.3 单行删除（仅草稿0/待审核1可执行）
                const deleteSingleSalesReturn = (row) => {
                    // 二次校验状态
                    if (row.orderStatus !== '0' && row.orderStatus !== '1') {
                        ElMessage({
                            type: 'error',
                            message: `当前「${getStatusText(row.orderStatus)}」状态不允许删除！`
                        });
                        return;
                    }
                    ElMessageBox.confirm(
                        `确定删除销售退货单 "${row.returnOrderNo}" 吗？删除后不可恢复！`,
                        '警告',
                        { type: 'error' }
                    ).then(async () => {
                        try {
                            const response = await axios.post(`/OmSalesReturn/Delete/${row.salesReturnId}`);
                            if (response.data.code === 200) {
                                tableData.value = tableData.value.filter(item => item.salesReturnId !== row.salesReturnId);
                                ElMessage({ type: 'success', message: '删除成功！' });
                            } else {
                                ElMessage({ type: 'error', message: response.data.msg || '删除失败' });
                            }
                        } catch (error) {
                            console.error('删除出错:', error);
                            ElMessage({ type: 'error', message: '删除失败，请重试' });
                        }
                    }).catch(() => {
                        ElMessage({ type: 'info', message: '已取消删除' });
                    });
                };

                // 5.4 撤销操作（仅已驳回2可执行）
                const handleRejectCancel = (row) => {
                    // 二次校验状态
                    if (row.orderStatus !== '2') {
                        ElMessage({
                            type: 'error',
                            message: `当前「${getStatusText(row.orderStatus)}」状态不允许撤销！`
                        });
                        return;
                    }
                    ElMessageBox.confirm(
                        `确定撤销驳回状态，将销售退货单"${row.returnOrderNo}"恢复为「待审核」吗？`,
                        '确认撤销',
                        { type: 'warning' }
                    ).then(async () => {
                        try {
                            const updateData = { ...row, orderStatus: '1' };
                            const response = await axios.post(`/OmSalesReturn/Edit/${row.salesReturnId}`, updateData);
                            if (response.data.code === 200) {
                                row.orderStatus = '1'; // 恢复为待审核状态
                                ElMessage({ type: 'success', message: '撤销成功！' });
                            } else {
                                ElMessage({ type: 'error', message: response.data.msg || '撤销失败' });
                            }
                        } catch (error) {
                            console.error('撤销出错:', error);
                            ElMessage({ type: 'error', message: '撤销失败，请重试' });
                        }
                    }).catch(() => {
                        ElMessage({ type: 'info', message: '已取消撤销' });
                    });
                };

                // 5.5 关闭销售退货单（仅已审核3可执行）
                const closeSalesReturn = (row) => {
                    ElMessageBox.confirm(
                        `确定关闭销售退货单"${row.returnOrderNo}"吗？`,
                        '确认关闭',
                        { type: 'warning' }
                    ).then(async () => {
                        try {
                            const updateData = { ...row, orderStatus: '4' };
                            const response = await axios.post(`/OmSalesReturn/Edit/${row.salesReturnId}`, updateData);
                            if (response.data.code === 200) {
                                row.orderStatus = '4'; // 改为关闭状态
                                ElMessage({ type: 'success', message: '销售退货单已关闭！' });
                            } else {
                                ElMessage({ type: 'error', message: response.data.msg || '关闭失败' });
                            }
                        } catch (error) {
                            console.error('关闭出错:', error);
                            ElMessage({ type: 'error', message: '关闭失败，请重试' });
                        }
                    }).catch(() => {
                        ElMessage({ type: 'info', message: '已取消关闭' });
                    });
                };

                // 5.6 启用销售退货单（仅已关闭4可执行）
                const enableSalesReturn = (row) => {
                    ElMessageBox.confirm(
                        `确定启用销售退货单"${row.returnOrderNo}"吗？`,
                        '确认启用',
                        { type: 'info' }
                    ).then(async () => {
                        try {
                            const updateData = { ...row, orderStatus: '3' };
                            const response = await axios.post(`/OmSalesReturn/Edit/${row.salesReturnId}`, updateData);
                            if (response.data.code === 200) {
                                row.orderStatus = '3'; // 改为已审核状态
                                ElMessage({ type: 'success', message: '销售退货单已启用！' });
                            } else {
                                ElMessage({ type: 'error', message: response.data.msg || '启用失败' });
                            }
                        } catch (error) {
                            console.error('启用出错:', error);
                            ElMessage({ type: 'error', message: '启用失败，请重试' });
                        }
                    }).catch(() => {
                        ElMessage({ type: 'info', message: '已取消启用' });
                    });
                };

                // 5.7 批量删除（仅草稿0/待审核1可执行）
                const deleteSalesReturn = () => {
                    if (selectedRows.value.length === 0) {
                        ElMessage({ type: 'warning', message: '请先选中需要删除的销售退货单！' });
                        return;
                    }
                    // 筛选可删除的销售退货单（状态0或1）
                    const canDeleteRows = selectedRows.value.filter(row =>
                        row.orderStatus === '0' || row.orderStatus === '1'
                    );
                    if (canDeleteRows.length === 0) {
                        ElMessage({ type: 'error', message: '仅「草稿」或「待审核」状态的销售退货单可删除！' });
                        return;
                    }
                    const deleteIds = canDeleteRows.map(row => row.salesReturnId);
                    ElMessageBox.confirm(
                        `确定删除选中的 ${canDeleteRows.length} 条销售退货单吗？`,
                        '警告',
                        { type: 'error' }
                    ).then(async () => {
                        try {
                            // 这里可以批量删除，或者循环删除
                            for (const id of deleteIds) {
                                await axios.post(`/OmSalesReturn/Delete/${id}`);
                            }
                            tableData.value = tableData.value.filter(row => !deleteIds.includes(row.salesReturnId));
                            ElMessage({ type: 'success', message: '删除成功！' });
                            selectedRows.value = [];
                        } catch (error) {
                            console.error('批量删除出错:', error);
                            ElMessage({ type: 'error', message: '删除失败，请重试' });
                        }
                    }).catch(() => {
                        ElMessage({ type: 'info', message: '已取消删除' });
                    });
                };

                // -------------------------- 6. 其他辅助方法 --------------------------
                // 日期格式化
                const formatDateTime = (date) => {
                    if (!date) return '';
                    const dt = new Date(date);
                    const year = dt.getFullYear();
                    const month = String(dt.getMonth() + 1).padStart(2, '0');
                    const day = String(dt.getDate()).padStart(2, '0');
                    const hours = String(dt.getHours()).padStart(2, '0');
                    const minutes = String(dt.getMinutes()).padStart(2, '0');
                    const seconds = String(dt.getSeconds()).padStart(2, '0');
                    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
                };

                // 日期格式化（仅日期）
                const formatDate = (date) => {
                    if (!date) return '';
                    const dt = new Date(date);
                    const year = dt.getFullYear();
                    const month = String(dt.getMonth() + 1).padStart(2, '0');
                    const day = String(dt.getDate()).padStart(2, '0');
                    return `${year}-${month}-${day}`;
                };

                // 退货单号点击跳转页面
                const jumpToDetail = (row) => {
                    ElMessage({ type: 'info', message: `跳转至销售退货单${row.returnOrderNo}的详情页` });
                    window.location.href = `/OmSalesReturn/Details?id=${row.salesReturnId}&pwd=114514`;
                };

                // 导出
                const exportTable = () => {
                    ElMessage({ type: 'success', message: '导出请求已触发，正在下载...' });
                };

                // 刷新
                const refreshTable = () => {
                    if (multipleTable.value) {
                        multipleTable.value.clearSelection();
                        selectedRows.value = [];
                    }
                    currentPage.value = 1;
                    refreshData(); // 重新加载数据
                    ElMessage({ type: 'success', message: '表格已刷新！' });
                };

                // 重置表单
                const resetForm = () => {
                    searchForm.value = {
                        returnOrderNo: '',
                        customerId: '',
                        sellerBy: '',
                        orderStatus: ''
                    };
                    refreshTable();
                };

                // 查询
                const searchTable = () => {
                    const returnOrderNo = searchForm.value.returnOrderNo || '';
                    const customerId = searchForm.value.customerId || '';
                    const sellerBy = searchForm.value.sellerBy || '';
                    const orderStatus = searchForm.value.orderStatus || '';

                    const filteredData = tableData.value.filter(row => {
                        const matchReturnOrderNo = returnOrderNo ?
                            row.returnOrderNo.includes(returnOrderNo) : true;
                        const matchCustomerId = customerId ? row.customerId == customerId : true;
                        const matchSellerBy = sellerBy ? row.sellerBy.includes(sellerBy) : true;
                        const matchOrderStatus = orderStatus ? row.orderStatus === orderStatus : true;
                        return matchReturnOrderNo && matchCustomerId && matchSellerBy && matchOrderStatus;
                    });

                    tableData.value = filteredData;
                    currentPage.value = 1;
                    ElMessage({ type: 'success', message: `查询到 ${filteredData.length} 条数据！` });
                };

                // 新增
                const addSalesReturn = () => {
                    ElNotification({ title: '提示', message: '跳转至新增销售退货单页面', type: 'info' });
                    window.location.href = '/OmSalesReturn/Create';
                };

                // 复制
                const copySalesReturn = () => {
                    if (selectedRows.value.length === 0) {
                        ElMessage({ type: 'warning', message: '请先选中需要复制的销售退货单！' });
                        return;
                    }
                    if (selectedRows.value.length > 1) {
                        ElMessage({ type: 'warning', message: '仅支持单条销售退货单复制！' });
                        return;
                    }
                    const targetRow = selectedRows.value[0];
                    ElNotification({ title: '复制销售退货单', message: `开始复制销售退货单：${targetRow.returnOrderNo}`, type: 'info' });
                };

                // 编辑（批量选择）
                const editSalesReturn = () => {
                    if (selectedRows.value.length === 0) {
                        ElMessage({ type: 'warning', message: '请先选中需要编辑的销售退货单！' });
                        return;
                    }
                    if (selectedRows.value.length > 1) {
                        ElMessage({ type: 'warning', message: '仅支持单条销售退货单编辑！' });
                        return;
                    }
                    const targetRow = selectedRows.value[0];
                    handleEdit(targetRow);
                };

                // 导入
                const importSalesReturn = () => {
                    ElNotification({ title: '导入销售退货单', message: '打开销售退货单导入窗口', type: 'info' });
                };

                // 页面挂载
                onMounted(() => {
                    refreshData();
                    loadCustomerOptions();
                });

                // 暴露数据和方法
                return {
                    // 搜索表单
                    searchForm,
                    customerOptions,

                    // 表格相关
                    tableData,
                    paginatedData,
                    selectedRows,
                    multipleTable,
                    handleSelectionChange,
                    handleEdit,
                    deleteSingleSalesReturn,
                    handleRejectCancel,
                    closeSalesReturn,
                    enableSalesReturn,
                    getStatusText,
                    getStatusClass,

                    // 分页相关
                    currentPage,
                    pageSize,
                    total,
                    handleSizeChange,
                    handleCurrentChange,

                    // 按钮方法
                    addSalesReturn,
                    editSalesReturn,
                    deleteSalesReturn,
                    copySalesReturn,
                    importSalesReturn,
                    exportTable,
                    refreshTable,
                    resetForm,
                    searchTable,
                    formatDateTime,
                    formatDate,
                    jumpToDetail
                };
            }
        });
        app.use(ElementPlus);
        app.mount('#app');
    </script>
</body>
</html>